package org.example.search.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.*;
import lombok.extern.slf4j.Slf4j;
import org.example.core.exception.CustomException;
import org.example.core.exception.ExceptionCode;
import org.example.search.constant.ElasticConstants;
import org.example.search.module.SkuEsModule;
import org.example.search.service.EsProductBackendService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @author 小杰_cc
 * @version 1.0
 */
@Service
@Slf4j
public class EsProductBackendServiceImpl implements EsProductBackendService {

    @Autowired
    private ElasticsearchClient elasticsearchClient;

    // 商品上架
    @Override
    public void skuUp(SkuEsModule skuEsModule) throws IOException {
        IndexRequest<SkuEsModule> indexRequest = IndexRequest.of(i ->
                i.index(ElasticConstants.PRODUCT_INDEX)
                        .id(skuEsModule.getSpuId().toString())
                        .document(skuEsModule)
        );
        elasticsearchClient.index(indexRequest);
    }

    // 商品下架
    @Override
    public void skusDown(List<Long> spuIds) {
        BulkRequest.Builder br = new BulkRequest.Builder();
        for (Long spuId : spuIds) {
            br.operations(op -> op.delete(d->d.index(ElasticConstants.PRODUCT_INDEX).id(spuId.toString())));
        }
        try {
            BulkResponse response = elasticsearchClient.bulk(br.build());
            if (response.errors()) {
                log.error("下架失败");
                throw new CustomException(ExceptionCode.SPU_DOWN_ERROR.getCode(), ExceptionCode.SPU_DOWN_ERROR.getMsg());
            }
        } catch (IOException e) {
            log.error("上架出现异常");
            throw new CustomException(ExceptionCode.SPU_DOWN_ERROR.getCode(), ExceptionCode.SPU_DOWN_ERROR.getMsg());
        }
    }

    // 重新上架
    @Override
    public void skusUpdate(SkuEsModule skuEsModule) {
        try{
            elasticsearchClient.update(update->
                            update.index(ElasticConstants.PRODUCT_INDEX)
                                    .id(skuEsModule.getSpuId().toString())
                                    .doc(skuEsModule)
                    ,SkuEsModule.class);
        }catch (IOException e){
            log.error("重新上架失败");
            throw new CustomException(ExceptionCode.SPU_UP_ERROR.getCode(), ExceptionCode.SPU_UP_ERROR.getMsg());
        }
    }
}